package com.example.smartmedicalsystem.controller;


import com.example.smartmedicalsystem.entity.MessageBoard;
import com.example.smartmedicalsystem.entity.User;
import com.example.smartmedicalsystem.repository.MessageBoardRepository;
import com.example.smartmedicalsystem.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequiredArgsConstructor
public class MessageBoardController {
    private final MessageBoardRepository messageBoardRepository;
    private final UserRepository userRepository;

    // 患者提交留言
    @PostMapping("/patient/message")
    public ResponseEntity<?> submitMessage(
            @AuthenticationPrincipal User user,
            @RequestBody String content
    ) {
        MessageBoard message = new MessageBoard();
        message.setPatient(user);
        message.setContent(content);
        message.setCreatedAt(LocalDateTime.now());
        messageBoardRepository.save(message);
        return ResponseEntity.ok().build();
    }

    // 管理员回复留言
    @PostMapping("/admin/message/{messageId}/reply")
    public ResponseEntity<?> replyMessage(
            @PathVariable Long messageId,
            @RequestBody String reply
    ) {
        MessageBoard message = messageBoardRepository.findById(messageId)
                .orElseThrow(() -> new RuntimeException("留言不存在"));
        message.setReply(reply);
        messageBoardRepository.save(message);
        return ResponseEntity.ok().build();
    }
    @GetMapping("/patient/messages")
    public List<MessageBoard> getPatientMessages(@AuthenticationPrincipal User user) {
        return messageBoardRepository.findByPatientId(user.getId());
    }

    @GetMapping("/admin/messages/unreplied")
    public List<MessageBoard> getUnrepliedMessages() {
        return messageBoardRepository.findByReplyIsNull();
    }
}